//In one area of your app
//Y.StyleSheet('MyApp').set('.module .messages', { display: 'none' });
//...
// In another area of your app
//Y.StyleSheet('MyApp').unset('.module .messages','display');

var m3958_hostname = "http://www.m3958.com/";
(function(){
	var hr = window.location.href;
	if(hr.indexOf('8888') == -1){
		if(hr.indexOf('debug=true') != -1){
			m3958_hostname = 'file:///E:/eclipse-jee-helios-SR1-win32/xyzcms/war/';
		}
	}else{
		m3958_hostname = 'http://127.0.0.1:8888/';
	}
})();

YUI({combine: true,
	comboBase: 'http://www.m3958.com/combo/yui?',
	modules :{
	'logindetector' : {
		requires:['cookie'],
		fullpath : m3958_hostname + 'wf/logindetect.js'
	}}
	}).use('logindetector','node','stylesheet','array-extras','event','button','button-group','autocomplete','datasource','datasource-jsonschema','querystring-stringify-simple','json',function(Y){
	var csses = Y.one('#csses'),
		nodeHtml = Y.one('#nodeHtml'),
		nodeId,
		stage = Y.one('#stage'),
	    saveBtn = Y.one('#save-css-style-btn'),
    	nameInput = Y.one('#css-style-name'),
    	cssNode = Y.one('#csses'),
    	htmlNode = Y.one('#nodeHtml'),
        inputNode = Y.one('#ac-input'),
    	rtpl = '&_fetchOwner=false&cat=open&published=true&name={query}',
    	newBt = Y.one('#new-css-style-btn'),
    	editingItem,loginDetector,ac,
    	showAll = Y.one('#showAll'),
    	openNode = Y.one('#css-style-open'),
    	publishedNode = Y.one('#css-style-published');
	
		publishedNode.hide();
	
	Y.on('click',function(e){
		e.preventDefault();
		var prev = stage.getContent(),
			success = true;
		
		stage.setContent(nodeHtml.get('value'));
		var cc = stage.get('children');
		if(cc.size() != 1){
			alert('最外围必须是一个（仅有一个）html标签！');
			success = false;
		}
		if(!success)
			stage.setContent(prev);
		var myStyleSheet = new Y.StyleSheet(csses.get('value'));
	},'#sureBt');
	
    var catGroupRadio = new Y.ButtonGroup({
        srcNode: '#catRadioContainer',
        type: 'radio'
    });
//    Y.log(catGroupRadio);
//    catGroupRadio.render();

    catGroupRadio.on('selectionChange', function(e){
        Y.log(e);
    });
    
    var m3958_host = "http://www.m3958.com/";
    var maxResults = 100;
    if(window.location.href.indexOf('8888') != -1){
    	m3958_host = "http://127.0.0.1:8888/";
    }
//    http://www.m3958.com/smartcfud?_modelName=com.m3958.firstgwt.server.model.Role&_operationType=FETCH&_subOperationType=MANY_TO_MANY&_isMaster=false&_relationModelName=com.m3958.firstgwt.server.model.User&_relationModelId=1&_relationPropertyName=roles
    
        var myDataSource = new Y.DataSource.Get({
            source: m3958_host + "smartcfud?_modelName=com.m3958.firstgwt.server.model.CssStyle&_operationType=FETCH&_mimeType=text/javascript;charset=utf-8&_jsonp=true&_startRow=0&_endRow=" + maxResults
        });
        
     // HTML template string that will be used for each ac result.
        var acTemplate =
        	'<div>{name} -- <input type="checkbox" {checked} class="ac-checkbox" id="ac-checkbox-{cid}"/></div>';

        // Custom formatter for tweets.
        function acFormatter(query, results) {
          // Iterate over the array of tweet result objects and return an
          // array of HTML strings.
          return Y.Array.map(results, function (result) {
            var cs = result.raw;

            // Use string substitution to fill out the tweet template and
            // return an HTML string for this result.
            return Y.Lang.sub(acTemplate, {
              name       : cs.name,
              checked        : cs.cat == 'open' ? 'checked' : '',
              cid : cs.id
            });
          });
        }
        
        var acCfg = {
        	  inputNode: '#ac-input',
        	  render   : true,
        	  minQueryLength : 0,
        	  maxResults : maxResults,
        	  requestTemplate: rtpl,
        	  resultListLocator: function (response) {
        		  if(Y.Lang.isArray(response) && response.length == 1){
        			  var res = response[0];
        			  return (res.response && res.response.data) || [];
        		  }else{
        			  return (response && response.response && response.response.data) || [];  
        		  }
        	  },
        	  resultTextLocator: function (result) {
        		    return result.name;
        	  },
        	  source: myDataSource
        };
      
       ac = new Y.AutoComplete(acCfg);
        
        ac.on('select',function(e){
        	var s = e.result.raw;
    		cssNode.set('value',s.css);
    		htmlNode.set('value',s.html);
    		nameInput.set('value',s.name);
    		editingItem = s;
    		stage.setContent(nodeHtml.get('value'));
    		var myStyleSheet = new Y.StyleSheet(csses.get('value'));
        	Y.log(s);
        });
        
        inputNode.on('focus',function(e){
        	var iput = e.target;
        	var v = iput.get('value');
        	if(iput.hasClass('not-focus-yet')){
        		iput.removeClass('not-focus-yet');
        		iput.set('value','');
        	}
        });
        
        showAll.on('click',function(e){
        	e.preventDefault();
        	if(inputNode.get('value')){
        		inputNode.set('value','');
        	}
    		ac.sendRequest('');
    		inputNode.focus();
        });
        
        newBt.on('click',function(e){
    		cssNode.set('value','');
    		htmlNode.set('value','');
    		nameInput.set('value','');
        	editingItem = null;
        });
    
    var tH = {
            start: function(id, args) {
                    ;
                   },
            complete: function(id, o, args) {
                        ;
                   },
            success: function(id, o, args) {
            			var res = Y.JSON.parse(o.responseText);
            			res = res.response;
            			if(res.status == 0 && res.data.length == 1){
            				editingItem = res.data[0];
            				alert('保存成功!');
            			}else{
            				alert('保存失败!');
            			}
                     },
            failure: function(id, o, args) {
                       ;
                     },
            end: function(id, args) {
            	;
            }
        };
    
    function getSaveCfg(args){
    	var data = {'_modelName':'com.m3958.firstgwt.server.model.CssStyle',
        		'_operationType':args.opType
    	};
    	
    	var css = cssNode.get('value'),
    		html = htmlNode.get('value'),
    		name = nameInput.get('value'),
    		published = publishedNode.get('checked'),
    		open = openNode.get('checked');
    		if(!published)published = false;
    		if(open){
    			open = 'open';
    		}else{
    			open = 'mine';
    		}
    	if('add' == args.opType){
    		data = Y.merge(data,{
    			'css':css,
    			'html' : html,
    			'name' : name,
    			'cat' : open,
    			'published' : published});
    	}else if('update' == args.opType){
    		var newItem = Y.merge(editingItem,{
    			'css':css,
    			'html' : html,
    			'name' : name,
    			'cat' : open,
    			'published' : published
    		});
    		data = Y.merge(data,newItem);
    	}
        var cfg = {
        		method : 'post',
                on: {
                    start: tH.start,
                    complete: tH.complete,
                    success: tH.success,
                    failure: tH.failure,
                    end: tH.end
                },
                data : data,
                context: tH,
                headers: {},
                arguments: {}
            };
        return cfg;
    }
    
    saveBtn.on('click',function(e){
    	if(!nameInput.get('value')){
    		alert('请输入名称！');
    		return;
    	}
    	if(!htmlNode.get('value') && !cssNode.get('value')){
    		alert('样式内容和HTML内容至少填写一个！');
    		return;
    	}
    	if(loginDetector && loginDetector.loginUser){
        	if(editingItem){//正在编辑
        		if(editingItem.creatorIds.indexOf(loginDetector.loginUser.id) == -1){//不是所有者
    				var c = window.confirm('这不是你创建的条目，将另存为你自己的条目，可以吗？');
    				Y.log(c);
    				if(c){
    					Y.io(m3958_host + 'smartcfud?', getSaveCfg({opType : 'add'}));
    				}
    			}else{//是所有者
    				Y.io(m3958_host + 'smartcfud?', getSaveCfg({opType:'update'}));
    			}
        	}else{
        		Y.io(m3958_host + 'smartcfud?', getSaveCfg({opType : 'add'}));
        	}
    	}else{
    		alert('您还没有登录呢');
    	}
    });
    
//    showAll.on('click',function(e){
//    	e.preventDefault();
//    	inputNode.focus();
//    	inputNode.set('value','');
//    });
    
    
    loginDetector =  new Y.M3958.LoginDetector({showMsg:false});
    loginDetector.on('loginDetectReady',function(e){
    	if(e.user){
            ac.set('requestTemplate','&_fetchOwner=true&name={query}');
            if(e.user.loginName == 'superman'){
            	publishedNode.show();
//            	ac.set('resultFormatter',acFormatter);
//            	Y.delegate('click',function(e){
//            		e.stopPropagation()
//            	},'.ac-checkbox');
//
//            	Y.delegate('valueChange',function(e){
//            		Y.log(e);
//            	},'.ac-checkbox');
            }
    	}
    });
    loginDetector.startDetect();
});

//_modelName:com.m3958.firstgwt.server.model.Article
//_relationModelId:10716
//siteId:8920
//_tz:Asia/Shanghai
//protectLevel:
//commentLevel:0
//content:xxxx
//defaultSectionId:10716
//title:xxxx
//_attachment_json:{"contentImgs":[], "attachments":[]}
//_operationType:add
//_oldValues:{}
//_componentId:isc_DynamicForm_4
//_dataSource:articleDS
//isc_metaDataPrefix:_
//isc_dataFormat:json
//Y.on('valueChange',function(e){
//	nodeId = e.newVal;
//
//	var ss = systemCsses[nodeId].split(';'),sindex = ss.length - 1;
//	var str = Y.Array.reduce(ss,'',function(pv,cv,index){
//		var cvt = Y.Lang.trim(cv),apd = ';\n';
//		if(sindex == index)apd = '';
//		if(cvt){
//			return pv + cvt + apd;
//		}else{
//			return pv;
//		}
//	});
//	/*
//	str = Y.Lang.trim(str);
//	if(str.lastIndexOf(';') == str.length - 1){
//		str = str.substring(0,str.length - 1);
//	}
//	*/
//	ss  = str.split('}');
//	sindex = ss.length - 1;
//	str = Y.Array.reduce(ss,'',function(pv,cv,index){
//		var apd = '\n}\n';
//		if(sindex == index)apd = '';
//		if(cv){
//			return pv + cv + apd;
//		}else{
//			return pv;
//		}
//		
//	});
//	ss = str.split('{');
//	sindex = ss.length - 1;
//	str = Y.Array.reduce(ss,'',function(pv,cv,index){
//		var apd = '{\n';
//		if(sindex == index)apd = '';
//		if(cv){
//			return pv + cv + apd;
//		}else{
//			return pv;
//		}
//		
//	});
//	csses.set('value',str);
//	stage.setContent(systemNodes[nodeId]);
//	nodeHtml.set('value',systemNodes[nodeId]);
//	var myStyleSheet = new Y.StyleSheet(csses.get('value'));
//},'#system-node-select');

